package com.ysu.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ysu.shop.pojo.Permission;
import com.ysu.shop.mapper.PermissionMapper;
import com.ysu.shop.pojo.RolePermission;
import com.ysu.shop.service.IPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysu.shop.service.IRolePermissionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 权限 服务实现类
 * </p>
 *
 * @author 耿志龙
 * @since 2020-10-01
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {
    @Resource
    private IRolePermissionService rolePermissionService;

    @Override
    public Object listByTree() {
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", 0);
        List<Permission> list = this.list(wrapper);
        for (Permission i : list) {
            getChildren(i);
        }
        return list;
    }

    /**
     * 参数为父权限对象 通过父权限获取子权限, 这里假设为2级
     *
     */
    private void getChildren(Permission permission) {
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", permission.getId());
        // List<Permission> list =this.list(wrapper) ;
        // for (Permission i : list) {
        //   if (permission.getType() != 0) {
        //     getChildren(permission);
        //   }
        // }
        permission.setChildren(this.list(wrapper));
    }

    @Override
    public Object userPermissionList(int id) {
        QueryWrapper<RolePermission> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", id);
        RolePermission rop = rolePermissionService.getOne(wrapper,false);
        if (rop == null) return null;
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", 0).inSql("id", rop.getPermissionId());
        List<Permission> list = this.list(queryWrapper);
        for (Permission i : list) {
            queryWrapper.clear();
            queryWrapper.eq("parent_id",i.getId()).inSql("id", rop.getPermissionId());
            i.setChildren(this.list(queryWrapper));
        }
        return list;
    }
}
